import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '@/views/Login'
// import Home from '@/views/Home'
// import User from '@/views/User'
// import Layout from '@/views/Layout'
// import Search from '@/views/Search'
// import SearchResult from '@/views/Search/SearchResult'
// import ArticleDetail from '@/views/ArticleDetail'
// import UserEdit from '@/views/User/UserEdit'
// import Chat from '@/views/Chat'
import { getToken } from '@/utils/token'

//总结：
//路由懒加载：为了让第一个页面，加载的app.js小一点，打开网页快一点
//思路：把组件对应js，分成若干个js，路由切换到那个页面，采取加载对应的js文件
Vue.use(VueRouter)

const routes = [{
        path: '/',
        redirect: '/layout/home' // 默认显示
    },
    // 登录
    {
        path: '/login',
        component: () =>
            import ( /* WebpackChunkName:"Login" */ '@/views/Login'),
        //路由的独享守卫
        beforeEnter: (to, from, next) => {
            // getToken().length > 0 &&
            if (getToken()?.length > 0 && to.path === '/login') {
                // next(false) //留在原地/什么都不写
                //想要近登录页不留在原地了，而是返回首页
                next('/layout/home')
            } else {
                next() //其他情况统统放行
            }
        }
    },
    // 底部tab栏
    {
        path: '/layout',
        component: () =>
            import ( /* WebpackChunkName:"Layout" */ '@/views/Layout'),
        children: [{
                path: 'home',
                component: () =>
                    import ( /* WebpackChunkName:"Home" */ '@/views/Home'),
                meta: {
                    scrollT: 0 //保存首页离开时，滚动条位置
                }
            },
            {
                path: 'user',
                component: () =>
                    import ( /* WebpackChunkName:"User" */ '@/views/User')
            }
        ]
    },
    // 搜索
    {
        path: '/search',
        component: () =>
            import ( /* WebpackChunkName:"Search" */ '@/views/Search')
    },
    // 搜索结果页
    {
        path: '/search_result/:kw',
        component: () =>
            import ( /* WebpackChunkName:"SearchResult" */ '@/views/Search/SearchResult')
    },
    // 文章详情
    {
        path: '/detail',
        component: () =>
            import ( /* WebpackChunkName:"ArticleDetail" */ '@/views/ArticleDetail')
    },
    // 用户资料
    {
        path: '/user_edit',
        component: () =>
            import ( /* WebpackChunkName:"UserEdit" */ '@/views/User/UserEdit')
    },
    // 聊天页面
    {
        path: '/chat',
        component: () =>
            import ( /* WebpackChunkName:"Chat" */ '@/views/Chat')
    }
]

const router = new VueRouter({
    routes
})

//路由-全局前置守卫（在路由发生真正跳转之前，执行此函数）
// 此函数可以决定路由是否跳转/取消/强制中断切换到别的路由
router.beforeEach((to, from, next) => {
    if (getToken()?.length > 0&&to.path === '/login') {
        next('/layout/home')
    } else {
        next() //其他情况统统放行
    }
})

export default router